<script setup>
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox,ElLoading  } from 'element-plus';
import { queryCouponsDetails,couponsActivityRule,couponsReceiveDetails } from '@/api/Marketing/coupon.js'
import { exportFile } from '@/utils/common.js';
import TopBar from '@/components/Topbar/index.vue';
import getRules from "@/validUtils";
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const topbarRef = ref(null);

const backValue = ref('CouponOrganizeIndex');
const tabName = ref("查看优惠券");

const formRef = ref(null);



const activityRef = ref(null);
const storeList = ref([]);
const groupType = ref("疗程")
const form = ref({
    name:"",
    remark:"",
    sendNum:"",
    price:"",
    useThreshold:0,
    reachPrice:"",
    useTime:0,
    useTimeValue:["",""],
    useDay:"",
    useStore:0,
    needValue:"1",
    storeList:[]
})

const activityScopeList = ['全部商品可用','指定商品可用','指定商品不可用']
const activityForm = ref({
    rangeType:0,
    cureList:[],
    comboList:[],
    projectList:[],
    productList:[]
})
const activeType = ref("基本信息");






const storePageConfig = ref({
    nowPage:1,
    pageSize:3,
    totalPage:0
})

const _getStoreLsit = async (page)=>{
    storePageConfig.value.nowPage = page;
    let parmas = {
        page:storePageConfig.value.nowPage,
        pageSize:storePageConfig.value.pageSize,
    }
    let result = await getLimitData(parmas,form.value.storeList);
    result =  JSON.parse(result);
    storeList.value = result.data
    storePageConfig.value.totalPage = Number(result.totalPage);
}

//获取分页后的数据
const getLimitData = (params,arr=[]) =>{
    const self = this;
    return new Promise((resolve,reject)=>{
        let returnData = JSON.parse(JSON.stringify(arr));
        params.page = params.page-1;
        let atPage = params.page * params.pageSize;
        returnData = returnData.splice(atPage,params.pageSize);
        resolve(JSON.stringify({
            data:returnData,
            totalPage:arr.length
        }));
    })
};


const groupTypeChange = ()=>{
    _getRangeList(1);
}



const rangePageConfig = ref({
    nowPage:1,
    pageSize:5,
    totalPage:0
})
const rangeList = ref([]);
const _getRangeList = async (page)=>{
    rangePageConfig.value.nowPage = page;
    let parmas = {
        page:rangePageConfig.value.nowPage,
        pageSize:rangePageConfig.value.pageSize,
    }
    let arr = [];
    if(groupType.value == "疗程"){
        arr = activityForm.value.cureList;
    }else if(groupType.value == "套餐"){
        arr = activityForm.value.comboList;
    }else if(groupType.value == "项目"){
        arr = activityForm.value.projectList;
    }else if(groupType.value == "产品"){
        arr = activityForm.value.productList;
    }

    let result = await getLimitData(parmas,arr);
    result = JSON.parse(result);
    rangeList.value = result.data;
    rangePageConfig.value.totalPage = Number(result.totalPage);
}
const searchData = ref({})

const formInline = ref([

])

const btnLefts = ref([
    {
        label:"导出",
        plain:false,
        type:"primary",
        show:true,
        plain:true,
        img:new URL("@/assets/icon/btn-export.png",import.meta.url),
        style:"border-color:#0C268C;color:#0C268C",
        click:async ()=>{
            const loading = ElLoading.service({
                lock: true,
                text: '导出中',
                background: 'rgba(255, 255, 255, 0.7)',
            })
            try{

              await exportFile(`/jy-marketing/mgmt/marketing/coupons/couponsReceiveDetExport`,'post',`优惠券领取详情`,{},searchData.value);
              loading.close()
            }catch(e){
              
              loading.close()
            }
        }
    },
])
const btnRights = ref([
])

const tableConfig = ref([
    {
      prop: "userName",
      label: "领取人姓名",
    },
    {
      prop: "phone",
      label: "手机号",
    },
    {
      prop: "receiveTime",
      label: "领取时间",
    },
    {
      prop: "applyTime",
      label: "使用时间",
    },
    {
        type: 'slot',
        label: '状态',
        prop: 'status',
        width: 140,
        needHeader: true,
        slotHeaderName: 'statusHeader',
        slotName: 'status'
    },

]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const seachTable = ref(null);

const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{

        let params = {
            ...formInline,
            couponsId:uuid.value,
            couponsStatus:status.value == -1?"":status.value
        }
        searchData.value = params;  
        let result = await couponsReceiveDetails(params);
 
        totalPage.value = Number(result.total);
        tableData.value = result.records;
        tableLoading.value = false;
    }catch(e){
        tableLoading.value = false;
    }
}
const status = ref(-1);
const handleCommand = (name) => {
    status.value = name;
    seachTable.value.initSearch();
};
const pageLoading = ref(false);
const uuid = ref(route.query.id || "");
const _queryCouponsDetails = async ()=>{
    pageLoading.value = true;
    try{
        let result = await queryCouponsDetails({couponsId:uuid.value});
        console.log(result,222);
        form.value = {
            name:result.couponsName,
            remark:result.couponsRemark,
            sendNum:result.releaseTotalNum,
            price:result.discountsAmount,
            useThreshold:result.thresholdType,
            reachPrice:result.thresholdAmount,
            useTime:result.usingType,
            useTimeValue:[result.usingStartTime,result.usingEndTime],
            useDay:result.usingDay,
            useStore:result.businessScope,
            needValue:"1",
            storeList:[]
        }

        activityForm.value.rangeType = result.activityScope;
        if(result.couponsStoreData && result.couponsStoreData.length>0){

            form.value.storeList = result.couponsStoreData.map(value=>{
                return {
                    id:value.storeId,
                    storeName:value.storeName,
                    isHall:value.businessType.includes(1),
                    isShop:value.businessType.includes(2),
                    hallId:'hall'+value.storeId,
                    shopId:'shop'+value.storeId,
                    brandId: value.brandId
                }
            })
            _getStoreLsit(1);
        }
        await _couponsActivityRule();
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
_queryCouponsDetails();

const _couponsActivityRule = async ()=>{
    pageLoading.value = true;
    try{
        let result = await couponsActivityRule({couponsId:uuid.value});
        result.forEach(lis=>{
            if(lis.activityType == 7){
         
                activityForm.value.cureList = lis.ruleData.map(info=>{
                    return {
                        courseName:info.classifyName,
                        id:info.id
                    }
                })
            }
            if(lis.activityType == 3){
                activityForm.value.comboList = lis.ruleData.map(info=>{
                    return {
                        comboName:info.classifyName,
                        id:info.id
                    }
                })
            }
            if(lis.activityType == 2){
                activityForm.value.projectList = lis.ruleData.map(info=>{
                    return {
                        projectName:info.classifyName,
                        id:info.id
                    }
                })
            }
            if(lis.activityType == 1){
                activityForm.value.productList = lis.ruleData.map(info=>{
                    return {
                        productName:info.classifyName,
                        id:info.id
                    }
                })
      
            }
        })
        _getRangeList(1);
  
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
onActivated(()=>{
    if(uuid.value !== route.query.id){
        uuid.value = route.query.id;
        activeStep.value = 0;
        _queryCouponsDetails();
    }

}) 
</script>
<template>
    <div class="page-contain">
        <TopBar :backValue="backValue" :tabName="tabName" ref="topbarRef">
        </TopBar>
        <div class="info-contain" v-loading="pageLoading">
            <div style="width:100%;padding-bottom:10px;">
                <el-radio-group v-model="activeType">
                    <el-radio-button label="基本信息" />
                    <el-radio-button label="活动规则" />
                    <el-radio-button label="发放详情" />
                </el-radio-group>
            </div>
            <div style="width:100%" v-if="activeType == '基本信息'">
                <el-form :model="form" label-width="130px" ref="formRef">
                    <div class="form-contain">
                        <el-form-item label="优惠券名称：" prop="name">
                            {{ form.name || '-' }}
                        </el-form-item>
                        <el-form-item label="备注名称：" prop="remark">
                            {{ form.remark || '-' }}
                        </el-form-item>
                        <el-form-item label="发放总量：" prop="sendNum">
                            {{ form.sendNum || '-' }}
                            <span class="unit-class">张</span>
                        </el-form-item>
                        <el-form-item label="优惠金额：" prop="price">
                            {{ form.price || '-' }}
                            <span class="unit-class">元</span>
                        </el-form-item>
                        <el-form-item label="使用门槛：" >

                            <span >
                                满{{ form.reachPrice }}元可用
                            </span>
                        </el-form-item>
                        <el-form-item label="使用时间：" >
                            <div class="inline-class" style="width:100%">
                                <span v-if="form.useTime == 0">
                                    {{ form.useTimeValue[0] }}
                                    ~
                                    {{ form.useTimeValue[1] }}
                                </span>
                                <span v-if="form.useTime == 1">
                                    领取后{{ form.useDay }}天内有效
                                </span>
                            </div>
                        </el-form-item>
                        <!-- <el-form-item label="适用门店及业务：" >
                            <span v-if="form.useStore == 0">全部门店及业务</span>
                            <span v-if="form.useStore == 1">指定门店及业务</span>
                        </el-form-item> -->
                        <el-form-item label="选择门店："  v-if="form.useStore == 1">

                            <div style="width:100%;padding-bottom:24px">
                            
                                <div style="width:500px;margin-top:8px" v-if="storeList && storeList.length>0">
                                    <el-table :data="storeList" style="width: 100%" stripe>
                                        <el-table-column prop="storeName" label="门店名称" width="200">
                                        </el-table-column>
                                        <!-- <el-table-column label="理疗馆">
                                            <template #default="{ row }">
                                                <span v-if="row.isHall">√</span>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="商城">
                                            <template #default="{ row }">
                                                <span v-if="row.isShop">√</span>
                                            </template>
                                        </el-table-column> -->
                                    </el-table>
                                    <div class="page">
                                        <el-pagination
                                            :current-page="storePageConfig.nowPage"
                                            :page-size="storePageConfig.pageSize"
                                            layout="prev, pager, next"
                                            :total="storePageConfig.totalPage"
                                            background
                                            @current-change="_getStoreLsit">
                                        </el-pagination>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div style="width:100%" v-if="activeType == '活动规则'">
                <el-form :model="activityForm" label-width="90px"  ref="activityRef">
                    <el-form-item label="活动范围：" >
                        <div>{{ activityScopeList[activityForm.rangeType] }}</div>
                        <div style="width:100%;" v-if="activityForm.rangeType !== 0">
                            <el-radio-group v-model="groupType" @change="groupTypeChange">
                                <!-- <el-radio-button label="疗程" /> -->
                                <el-radio-button label="套餐" />
                                <el-radio-button label="项目" />
                                <el-radio-button label="产品" />
                            </el-radio-group>
                        </div>
                        <div style="width:500px;margin-top:8px" v-if="rangeList && rangeList.length>0">
                            <!-- <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '疗程'">
                                <el-table-column prop="courseName" label="疗程名称" >
                                </el-table-column>

                            </el-table> -->
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '套餐'">
                                <el-table-column prop="comboName" label="套餐名称">
                                </el-table-column>
         
                            </el-table>
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '项目'">
                                <el-table-column prop="projectName" label="项目名称">
                                </el-table-column>
            
                            </el-table>
                            <el-table :data="rangeList" style="width: 100%" stripe v-if="groupType == '产品'">
                                <el-table-column prop="productName" label="产品名称">
                                </el-table-column>
                            </el-table>
                            <div class="page">
                                <el-pagination
                                    :current-page="rangePageConfig.nowPage"
                                    :page-size="rangePageConfig.pageSize"
                                    layout="prev, pager, next"
                                    :total="rangePageConfig.totalPage"
                                    background
                                    @current-change="_getRangeList">
                                </el-pagination>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>

            </div>
            <div style="width:100%;height:calc(100% - 52px)" v-if="activeType == '发放详情'">
                <SeachTable 
                    :tableType="2"
                    :tableWidth="100"
                    ref="seachTable"
                    :forms="formInline"
                    :btnLefts="btnLefts"
                    :btnRights="btnRights"
                    :tableLoading="tableLoading"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :totalPage="totalPage"
                    @handlerSearch="handlerSearch"
                    :showLine="false"
                    :tableIndex="true"
                    >
                    <template #status="{ row }">
                        {{ row.couponsStatus }}
                    </template>
                    <template #statusHeader>
                        <el-dropdown @command="handleCommand">
                            <div class="status-div">
                                状态
                                <img src="@/assets/images/shaixuan3.png" alt="">
                            </div>
                            <template #dropdown>
                                <el-dropdown-menu >
                                    <el-dropdown-item :command="-1">全部</el-dropdown-item>
                                    <el-dropdown-item :command="0">待使用</el-dropdown-item>
                                    <el-dropdown-item :command="1">已使用</el-dropdown-item>
                                    <el-dropdown-item :command="2">已失效</el-dropdown-item>
                                </el-dropdown-menu>
                                </template>
                        </el-dropdown>
                    </template>
                </SeachTable>
            </div>
        </div>
    </div>

</template>
<style lang="less" scoped>
.status-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color:#000;
    position: relative;
    top:3px;
    img{
        width: 14px;
        height: 14px;
        cursor: pointer;
        margin-left:4px;
    }
}
.page{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  margin-top:8px;
}
:deep(.el-table__inner-wrapper::before){
    display:none;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}

:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
.inline-class{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.unit-class{
    font-size: 14px;
    color: #000000;
    font-weight: 400;
    line-height: 32px;
    margin-left:8px;
}
.form-contain{
    width: 100%;

}
.page-contain{
    width: 100%;
    height: 100%;
}
.info-contain{
    width: 100%;
    height: calc(100% - 48px);
    box-sizing: border-box;
    padding:16px 24px;
    :deep(.el-form-item){
        margin-bottom:0;
    }
    :deep(.el-form-item__label){
        padding:0;
    }
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3480FF;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
:deep(.search-line){
    padding:0;
}
:deep(.search-table .table){
    padding:0;
    padding-top:12px;
}
:deep(.search-table .btn-area){
    padding:0;

}
</style>